package com.hui.account.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hui.account.R;
import com.hui.account.adapter.RecordAdapter;
import com.hui.account.database.SQLManage;
import com.hui.account.dialog.MoreDialog;
import com.hui.account.entity.RecordEntity;
import com.hui.account.utils.ButtonUtils;
import com.hui.account.utils.CommonUtils;
import com.hui.account.entity.custom.CustomPasswordTransformationMethod;
import com.hui.account.utils.TimeUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 首页
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Context context;

    boolean flag = true;

    Button addRecord; // 记一笔

    ImageView search; // 首页搜索

    ListView recordList; // 记录列表

    ImageButton more; // 首页更多选项

    List<RecordEntity> data; // 欠款记录

    RecordAdapter adapter;

    int year, month, day;

    /* 首页头布局控件 */
    View topView; // 头布局页面

    ImageView eye; // 眼睛

    LinearLayout topLayout;

    TextView personNumber, totalMoney, todayTime;

    SharedPreferences preferences; // preferences：共享参数，存储选中的欠款单信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
        setContentView(R.layout.activity_main);

        // 1、设置屏幕顶部字体颜色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        // 2、获取当前时间
        initTime();

        // 3、初始化页面
        initView();

        // 4、引入首页头布局
        topView();

        // 5、preferences：共享参数初始化
        preferences = getSharedPreferences("shareParam", Context.MODE_PRIVATE);

        // 6、设置 ListView点击事件
        onClickRecordList();

        // 7、引入欠款记录适配器
        data = new ArrayList<>();
        adapter = new RecordAdapter(this, data);
        recordList.setAdapter(adapter);
    }

    /**
     * Activity加载时执行
     */
    @Override
    protected void onResume() {
        super.onResume();

        // 1、加载 top数据
        loadTodData();

        // 2、加载 欠款记录
        loadRecordData();
    }

    /**
     * 获取当前时间
     */
    private void initTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 初始化页面
     */
    private void initView() {
        search = findViewById(R.id.main_search);
        more = findViewById(R.id.main_more_btn);
        recordList = findViewById(R.id.main_list_record);
        addRecord = findViewById(R.id.main_add_record_btn);

        // 监听点击事件
        more.setOnClickListener(this);
        search.setOnClickListener(this);
        addRecord.setOnClickListener(this);
    }

    /**
     * 引入首页头布局
     */
    @SuppressLint("InflateParams")
    private void topView() {
        // 1、引入首页头布局
        topView = getLayoutInflater().inflate(R.layout.item_main_top, null);

        // 2、ListView上方添加头布局
        recordList.addHeaderView(topView);

        eye = findViewById(R.id.main_top_eye);
        personNumber = findViewById(R.id.main_top_value1);
        totalMoney = findViewById(R.id.main_top_value2);
        todayTime = findViewById(R.id.main_top_time);
        topLayout = findViewById(R.id.main_top);

        eye.setOnClickListener(this);
        topLayout.setOnClickListener(this);
    }

    /**
     * 加载 top数据
     */
    @SuppressLint("SetTextI18n")
    private void loadTodData() {
        try {
            todayTime.setText(TimeUtils.getTodayDate());

            // 1、查询欠账总人数
            int recordUserCount = SQLManage.getRecordUserCount();
            personNumber.setText(recordUserCount + " 人");


            // 2、查询欠款总金额
            BigDecimal value = getRecordTotalMoney();
            totalMoney.setText(CommonUtils.MONEY + value);
        } catch (Exception e) {
            Log.e(CommonUtils.TAG, "===> 【首页】 Top数据" + e.getMessage());
        }
    }

    /**
     * 计算欠款总金额
     */
    public BigDecimal getRecordTotalMoney() {
        BigDecimal totalMoney = new BigDecimal(0);
        int curPage = 0; // 起始页码
        int pageSize = 500; // 每页查询最大数
        boolean flag = true;
        while (flag) {
            List<BigDecimal> values = SQLManage.getRecordTotalMoney(curPage, pageSize);
            if (values.size() > 0) {
                for (BigDecimal value : values) {
                    totalMoney = totalMoney.add(value);
                }
                if (values.size() == pageSize) {
                    curPage += pageSize;
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
        return totalMoney;
    }

    /**
     * 加载 欠款记录
     */
    private void loadRecordData() {
        try {
            // 查询本月欠款记录
            List<RecordEntity> list = SQLManage.getMonthRecords(year, month);
            if (list.size() > 0) {
                data.clear();
                data.addAll(list);
                adapter.notifyDataSetChanged();
            } else {
                data.clear();
                adapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            Log.e(CommonUtils.TAG, "===> 【首页】 欠款单列表数据" + e.getMessage());
        }
    }

    /**
     * 明文/密文 切换显示头布局眼睛
     */
    @SuppressLint("SetTextI18n")
    private void toggleEye() {
        if (flag) {
            CustomPasswordTransformationMethod instance = new CustomPasswordTransformationMethod();
            personNumber.setText("0 人");
            totalMoney.setText(CommonUtils.MONEY + "0");
            personNumber.setTransformationMethod(instance);
            totalMoney.setTransformationMethod(instance);
            eye.setImageResource(R.drawable.ic_hide);
            flag = false;
        } else {
            loadTodData(); // 重新加载数据
            HideReturnsTransformationMethod instance = new HideReturnsTransformationMethod();
            personNumber.setTransformationMethod(instance);
            totalMoney.setTransformationMethod(instance);
            eye.setImageResource(R.drawable.ic_eye);
            flag = true;
        }
    }

    /**
     * 欠款单适配器点击事件
     */
    private void onClickRecordList() {
        recordList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!ButtonUtils.isFastDoubleClick()) {
                    try {
                        // 1、获取到当前记录
                        RecordEntity record = data.get(i - 1);

                        // 2、将数据存入共享参数
                        SharedPreferences.Editor edit = preferences.edit();
                        edit.putString("selectRecord", new Gson().toJson(record));
                        edit.commit();

                        startActivity(new Intent(context, RecordModActivity.class));
                    } catch (Exception e) {
                        Log.e(CommonUtils.TAG, "===> 【首页】 欠款单详情" + e.getMessage());
                    }
                }
            }
        });
    }

    /**
     * 点击事件
     */
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_search:
                if (!ButtonUtils.isFastDoubleClick()) {
                    startActivity(new Intent(this, SearchActivity.class));
                }
                break;
            case R.id.main_more_btn:
                MoreDialog dialog = new MoreDialog(this);
                dialog.show();
                dialog.setDialogSize();
                break;
            case R.id.main_add_record_btn:
                if (!ButtonUtils.isFastDoubleClick()) {
                    // 清空共享参数值
                    SharedPreferences preferences = getSharedPreferences("shareParam", Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = preferences.edit();
                    edit.putString("selectUser", "");
                    edit.commit();

                    startActivity(new Intent(this, RecordActivity.class));
                }
                break;
            case R.id.main_top_eye:
                toggleEye();
                break;
            case R.id.main_top:
                break;
        }
    }
}